import { Module } from "vuex";
import { decodeJwtToken } from "../../util/jwt";

// 提前获取用户登录信息
let user = null as any;
const token = localStorage.getItem("userToken");
if (token) user = decodeJwtToken(token);

const sessionModule: Module<any, any> = {
  state: () => ({
    user,
    // 背景图设置
    bgImage: "",
  }),
  mutations: {
    // 记录用户登录
    RememberLogin: (state, { user }) => {
      state.user = user;
    },
    //用户登出
    Logout: (state) => {
      // localStorage.removeItem('userToken')
      state.user = null;
    },
    // 设置应用背景图
    setBgImage: (state, { image }) => {
      state.bgImage = image;
    },
  },

  actions: {
    Login: ({ commit }, { username, password }) => {
      // 没有接口暂时固定写死
      const res = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJhdmF0YXIiOiJodHRwczovL2ltYWdlcy51bnNwbGFzaC5jb20vcGhvdG8tMTU5NDYxNjgzODk1MS1jMTU1ZjhkOTc4YTA_aXhsaWI9cmItMS4yLjEmaXhpZD1Nbnd4TWpBM2ZEQjhNSHh3YUc5MGJ5MXdZV2RsZkh4OGZHVnVmREI4Zkh4OCZhdXRvPWZvcm1hdCZmaXQ9Y3JvcCZ3PTEzNTAmcT04MCJ9.cyUNflDi9Tm34ZpoUZ2p1tBS7yurWh4ggG_ckwjvmTY`;
      // 解析jwtToken
      const user = decodeJwtToken(res);

      if (!user) {
        return Promise.reject("登录凭证不合法");
      }
      // 将token存入localStorage
      // localStorage.setItem('userToken', res)
      // commit('RememberLogin', { user })
      // return Promise.resolve(user)
      return Promise.resolve({});
    },
    // 用户登出
    Logout: ({ commit }) => {
      commit("Logout");
    },
  },
  getters: {},
};

export default sessionModule;
